package com.tjbank.cssys.framework.base.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.UUID;

/**
 * 生成ID
 *
 * Package : com.tansun.magicube.framework.base.util
 *
 * @author -- lijiangtao 2020年5月15日 下午3:37:53
 *
 */
public class GeneratIDUtil {

    // 起始的时间戳
    private final static long START_STMP = 1480166465631L;
    /** 每一部分占用的位数 */
    // 序列号占用的位数
    private final static long SEQUENCE_BIT = 12;
    // 机器标识占用的位数
    private final static long MACHINE_BIT = 5;
    // 数据中心占用的位数
    private final static long DATACENTER_BIT = 5;
    // 每一部分的最大值
//    private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);// 31
//    private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);// 31
    private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);// 4095
    // 每一部分向左的位移
    private final static long MACHINE_LEFT = SEQUENCE_BIT;// 12
    private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;// 12 + 5 = 17
    private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT; // 17 + 5 = 22
    // 数据中心
    private final static long datacenterId = 1;
    // 机器标识
    private final static long machineId = 1;
    // 序列号
    private static long sequence = 0L;
    // 上一次时间戳
    private static long lastStmp = -1L;

    /**
     * UUID
     * @return
     */
    public static String getUUId() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * snowflake
     */
    public static synchronized long nextId() {
        long currStmp = getNewstmp();
        if (currStmp < lastStmp) {
            throw new RuntimeException("Clock moved backwards.  Refusing to generate id");
        }
        // 相同毫秒内，序列号自增
        if (currStmp == lastStmp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            // 同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currStmp = getNextMill();
            }
        } else {
            // 不同毫秒内，序列号置为0
            sequence = 0L;
        }
        lastStmp = currStmp;
        return (currStmp - START_STMP) << TIMESTMP_LEFT // 时间戳部分
                | datacenterId << DATACENTER_LEFT// 数据中心部分
                | machineId << MACHINE_LEFT // 机器标识部分
                | sequence; // 序列号部分
    }

    /**
     * 随机数的哈希值
     */
    public static String gethexEncode() {
        try {
            SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
            String randomNum = Integer.valueOf(prng.nextInt()).toString();
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
            byte[] result = messageDigest.digest(randomNum.getBytes());
            StringBuilder sb = new StringBuilder();
            char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            for (int idx = 0; idx < result.length; ++idx) {
                byte b = result[idx];
                sb.append(digits[(b & 0xf0) >> 4]);
                sb.append(digits[b & 0x0f]);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException ex) {
            System.err.println(ex);
        }
        return null;
    }

    /** ============================================ **/

    private static long getNewstmp() {
        return System.currentTimeMillis();
    }

    private static long getNextMill() {
        long mill = getNewstmp();
        while (mill <= lastStmp) {
            mill = getNewstmp();
        }
        return mill;
    }


}
